package com.gpframework.module.service;

import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.enums.StoreSysConfig;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.module.base.domain.vo.BaseStoreConfigVo;
import com.gpframework.module.base.mapper.BaseStoreConfigMapper;
import com.gpframework.module.common.domain.req.CommonStoreConfigValueReq;
import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.service.system.ISysMenuService;
import com.gpframework.module.service.system.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @Author gpframework
 */
@Component
public class SysPermissionService {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private BaseStoreConfigMapper baseStoreConfigMapper;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.whetherAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getBrandUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        CommonStoreConfigValueReq configValueReq = new CommonStoreConfigValueReq();
        configValueReq.setBrandId(user.getBrandId());
        configValueReq.setStoreId(BrandConstants.DEFAULT_BRAND_ID);
        configValueReq.setKey(StoreSysConfig.SYS_BRAND_MENU.toString());
        BaseStoreConfigVo brandConfig = baseStoreConfigMapper.getInfo(configValueReq);
        if (user.isAdmIN()) {
            perms.add("*:*:*");
            return perms;
        }

        // 管理员拥有所有权限
        if (!StringUtil.isEmpty(brandConfig) && YesNoEnum.YES.getKey().equals(brandConfig.getStoreKey()) && user.whetherAdmin()) {
            perms.add("*:*:*");
        } else {
            perms.addAll(menuService.selectMenuPermsByUserId(user.getBrandUserId()));
        }
        return perms;
    }
}
